import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'


let camera, scene, renderer
let textureCube
let count = 500
let spheres = []

initScene()
initAxesHelper()
initMeshes()
initCamera()
initRenderer()
enableControls()
animate()

window.addEventListener('resize',
  function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight)
  }
)

function initScene(params) {
    scene = new THREE.Scene()
    //放图片
    const urls = [
        'textures/cube/px.png',
        'textures/cube/nx.png',
        'textures/cube/py.png',
        'textures/cube/ny.png',
        'textures/cube/pz.png',
        'textures/cube/nz.png',

    ]
    textureCube = new THREE.CubeTextureLoader().load(urls)
    scene.background = textureCube
}

function initAxesHelper(params) {
    // scene.add(new THREE.AxesHelper(1))
}

function initMeshes(params) {
    const geometry = new THREE.SphereGeometry(0.1, 64, 64);
    const material = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        envMap:textureCube   
    })
    for (let i = 0; i < count; i++){
        const mesh = new THREE.Mesh(geometry, material)
        mesh.position.x = Math.random() * 10 - 5
        mesh.position.y = Math.random() * 10 - 5
        mesh.position.z = Math.random() * 10 - 5
        //把小球变随机  1-4倍随机
        mesh.scale.x=mesh.scale.y=mesh.scale.z=Math.random() * 3 +1
        scene.add(mesh)
        spheres.push(mesh)
     }
}


function initCamera(params) {
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 100)
    camera.position.z = 3
}

function initRenderer(params) {
    renderer = new THREE.WebGLRenderer({ antialias: true, })
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)
}

function enableControls(params) {
    const controls = new OrbitControls(camera,renderer.domElement)
}
function animate(){
    requestAnimationFrame(animate)
    render()
}

function render(params) {
    const timer = 0.0001 * Date.now()
    for (let i = 0; i < count; i++){
        const s = spheres[i]
        s.position.x = 5 * Math.cos(timer + i)
        s.position.y = 5 * Math.sin(timer + i * 1.2)
    }
    renderer.render(scene, camera)
    
}